package cn.foolishbird.business.abstraction.iassert;

import cn.foolishbird.business.abstraction.exception.base.BaseException;
import cn.foolishbird.business.abstraction.exception.BusinessException;
import cn.foolishbird.business.abstraction.iassert.condition.Condition;
import cn.foolishbird.business.abstraction.iassert.condition.NotNullCondition;
import cn.foolishbird.business.abstraction.iassert.einfo.EInfo;

import java.lang.reflect.Constructor;

/**
 * 业务断言工具类
 *
 * @author Eric
 * @version 1.0
 * @date 2019-12-13
 */
public class IAssert {

    /**
     * 例子方法，空值判断
     *
     * @param obj  1
     * @param info 2
     * @return void
     * @throws
     * @author Eric
     * @date 2019/12/13
     **/
    public static void nullAssert(Object obj, EInfo info) throws Exception {
        iAssert(new NotNullCondition<Object>(obj), info, BusinessException.class);
    }

    /**
     * 条件接口 基础方法，适用于一些条件判断较复杂的
     * 实现条件接口后，缩小业务部分代码
     *
     * @param condition 条件接口
     * @param info      错误信息
     * @param exception 错误类型
     * @return void
     * @throws
     * @author Eric
     * @date 2019/12/13
     **/
    public static <T extends BaseException> void iAssert(Condition condition, EInfo info, Class<T> exception) throws Exception {
        iAssert(condition.condition(), info, exception);
    }

    /**
     * @param condition 1
     * @param info      2
     * @return void
     * @throws
     * @author Eric
     * @date 2019/12/13
     **/
    public static <T extends BaseException> void iAssert(boolean condition, EInfo info) throws Exception {
        iAssert(condition, info, BusinessException.class);
    }

    /**
     * 断言基础方法
     *
     * @param condition 条件
     * @param info      错误信息
     * @param exception 错误类型
     * @return void
     * @throws
     * @author Eric
     * @date 2019/12/13
     **/
    public static <T extends BaseException> void iAssert(boolean condition, EInfo info, Class<T> exception) throws Exception {
        if (condition) {
            Constructor<T> con = exception.getConstructor(int.class, String.class);
            BaseException exce = null;
            if (con != null) {
                exce = con.newInstance(info.code(), info.message());
            } else {
                exce = new BusinessException(info.code(), info.message());
            }
            throw exce;
        }
    }
}
